#include "MainWindow.h"
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QLabel>

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
{
    setupUI();
    createMenus();
    createToolBar();
    createStatusBar();
}

void MainWindow::setupUI()
{
    // 设置窗口属性
    setWindowTitle("Qt计算器 - 基于QMainWindow");
    setMinimumSize(300, 400);

    // 创建中央部件
    setupCentralWidget();
}

void MainWindow::setupCentralWidget()
{
    // 创建中央部件
    QWidget* centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);

    // 创建主布局
    QVBoxLayout* mainLayout = new QVBoxLayout(centralWidget);

    // 创建显示区域
    display = new QLineEdit();
    display->setReadOnly(true);
    display->setAlignment(Qt::AlignRight);
    display->setMaxLength(15);
    display->setStyleSheet("QLineEdit { font-size: 18px; padding: 5px; }");
    mainLayout->addWidget(display);

    // 创建按钮网格布局
    QGridLayout* buttonLayout = new QGridLayout();

    // 定义按钮文本
    QStringList buttonTexts = {
        "7", "8", "9", "/",
        "4", "5", "6", "*",
        "1", "2", "3", "-",
        "0", "C", "=", "+"
    };

    // 创建按钮
    int position = 0;
    for (int row = 0; row < 4; ++row) {
        for (int col = 0; col < 4; ++col) {
            QPushButton* button = new QPushButton(buttonTexts[position]);
            button->setFixedSize(60, 60);
            button->setStyleSheet(
                "QPushButton {"
                "    font-size: 16px;"
                "    font-weight: bold;"
                "    border: 1px solid #ccc;"
                "    border-radius: 5px;"
                "    background-color: #f0f0f0;"
                "}"
                "QPushButton:hover {"
                "    background-color: #e0e0e0;"
                "}"
                "QPushButton:pressed {"
                "    background-color: #d0d0d0;"
                "}"
            );

            buttonLayout->addWidget(button, row, col);

            // 分类按钮
            if (buttonTexts[position] >= "0" && buttonTexts[position] <= "9") {
                numberButtonList.append(button);
                connect(button, &QPushButton::clicked, this, &MainWindow::numberClicked);
            }
            else {
                operatorButtonList.append(button);
                connect(button, &QPushButton::clicked, this, &MainWindow::operatorClicked);
            }

            position++;
        }
    }

    mainLayout->addLayout(buttonLayout);
}

void MainWindow::createMenus()
{
    // 文件菜单
    QMenu* fileMenu = menuBar()->addMenu("文件(&F)");

    newAction = fileMenu->addAction("新建(&N)");
    newAction->setShortcut(QKeySequence::New);
    connect(newAction, &QAction::triggered, this, &MainWindow::onNew);

    fileMenu->addSeparator();

    exitAction = fileMenu->addAction("退出(&Q)");
    exitAction->setShortcut(QKeySequence::Quit);
    connect(exitAction, &QAction::triggered, this, &MainWindow::onExit);

    // 编辑菜单
    QMenu* editMenu = menuBar()->addMenu("编辑(&E)");
    QAction* clearAction = editMenu->addAction("清除(&C)");
    clearAction->setShortcut(QKeySequence("Ctrl+L"));
    connect(clearAction, &QAction::triggered, this, &MainWindow::onClear);

    // 帮助菜单
    QMenu* helpMenu = menuBar()->addMenu("帮助(&H)");

    aboutAction = helpMenu->addAction("关于(&A)");
    connect(aboutAction, &QAction::triggered, this, &MainWindow::onAbout);
}

void MainWindow::createToolBar()
{
    QToolBar* mainToolBar = addToolBar("主工具栏");
    mainToolBar->setMovable(false);

    // 添加工具栏按钮
    QAction* clearToolAction = mainToolBar->addAction("清除");
    clearToolAction->setToolTip("清除计算器显示");
    connect(clearToolAction, &QAction::triggered, this, &MainWindow::onClear);

    mainToolBar->addSeparator();

    QAction* aboutToolAction = mainToolBar->addAction("关于");
    aboutToolAction->setToolTip("显示关于信息");
    connect(aboutToolAction, &QAction::triggered, this, &MainWindow::onAbout);
}

void MainWindow::createStatusBar()
{
    statusBar()->showMessage("就绪 - 请输入表达式");

    // 添加永久部件
    QLabel* versionLabel = new QLabel("v1.0");
    statusBar()->addPermanentWidget(versionLabel);
}

void MainWindow::numberClicked()
{
    QPushButton* button = qobject_cast<QPushButton*>(sender());
    if (button) {
        QString number = button->text();
        display->setText(display->text() + number);
        statusBar()->showMessage("输入数字: " + number);
    }
}

void MainWindow::operatorClicked()
{
    QPushButton* button = qobject_cast<QPushButton*>(sender());
    if (button) {
        QString op = button->text();

        if (op == "C") {
            onClear();
        }
        else if (op == "=") {
            calculateResult();
        }
        else {
            // 存储第一个数字和操作符
            if (!display->text().isEmpty()) {
                firstNumber = display->text().toDouble();
                currentOperator = op;
                display->clear();
                statusBar()->showMessage("操作符: " + op + ", 请输入第二个数字");
            }
        }
    }
}

void MainWindow::calculateResult()
{
    if (display->text().isEmpty() || currentOperator.isEmpty()) {
        return;
    }

    bool ok;
    double secondNumber = display->text().toDouble(&ok);

    if (!ok) {
        QMessageBox::warning(this, "错误", "无效的数字输入!");
        statusBar()->showMessage("错误: 无效的数字输入");
        return;
    }

    double result = 0;
    QString operation;

    // 根据操作符执行计算
    if (currentOperator == "+") {
        result = firstNumber + secondNumber;
        operation = "加法";
    }
    else if (currentOperator == "-") {
        result = firstNumber - secondNumber;
        operation = "减法";
    }
    else if (currentOperator == "*") {
        result = firstNumber * secondNumber;
        operation = "乘法";
    }
    else if (currentOperator == "/") {
        if (secondNumber == 0) {
            QMessageBox::warning(this, "错误", "除数不能为零!");
            statusBar()->showMessage("错误: 除数不能为零");
            return;
        }
        result = firstNumber / secondNumber;
        operation = "除法";
    }
    else {
        return; // 没有操作符
    }

    display->setText(QString::number(result));
    currentOperator = "";

    statusBar()->showMessage(operation + "计算完成: " + QString::number(result));
}

void MainWindow::onNew()
{
    display->clear();
    firstNumber = 0;
    currentOperator = "";
    statusBar()->showMessage("新建计算 - 请输入表达式");
}

void MainWindow::onExit()
{
    close();
}

void MainWindow::onAbout()
{
    QMessageBox::about(this, "关于Qt计算器",
        "<h3>Qt计算器 v1.0</h3>"
        "<p>基于QMainWindow的简单计算器应用</p>"
        "<p>演示了：</p>"
        "<ul>"
        "<li>QMainWindow的基本用法</li>"
        "<li>菜单栏、工具栏、状态栏</li>"
        "<li>信号与槽机制</li>"
        "<li>布局管理</li>"
        "</ul>"
        "<p>使用Qt " QT_VERSION_STR " 构建</p>");
}

void MainWindow::onClear()
{
    display->clear();
    firstNumber = 0;
    currentOperator = "";
    statusBar()->showMessage("已清除");
}